package com.wnhz.work.yz.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.adapter.AllocationAdapter;
import com.wnhz.work.yz.adapter.BashRoomAdapter;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.AllocationBean;
import com.wnhz.work.yz.bean.BathRoomSkuBean;
import com.wnhz.work.yz.constant.Constants;
import com.wnhz.work.yz.molder.EntiretyShoppingMolder;
import com.wnhz.work.yz.utils.BroadCastReceiverUtil;
import com.wnhz.work.yz.utils.BroadCastReceiverUtil.OnReceiveBroadcast;
import com.wnhz.work.yz.utils.MyUtils;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 浴室列表
 */
public class BashRoomListActivity extends BaseActivity implements View.OnClickListener, OnReceiveBroadcast {

    private TextView title;
    private TextView tv_right;
    private ListView my_recycler;
//    private PullToRefreshScrollView myScroll;

    private String goods_name;
    private BaseRVAdapter mBathRommAdapter;
    private List<BathRoomSkuBean.InfoEntity> bathRoomList = new ArrayList<>();
    private List<BathRoomSkuBean.InfoEntity> bathRoomList2 = new ArrayList<>();
    private String packageId;//浴室id
    private String money;//价格
    private String skuId;//属性id
    private String type;//类型
    private EntiretyShoppingMolder shoppingMolder;
    private int chooseNum;
    private int deleteNum;
    BashRoomAdapter mAdapter;

    BroadcastReceiver broadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bash_room_list);

        if (null != getIntent() && !TextUtils.isEmpty(getIntent().getStringExtra("goods_name"))){
            goods_name = getIntent().getStringExtra("goods_name");
        }
        title = (TextView) findViewById(R.id.view_main_middle_title);
        if (TextUtils.isEmpty(goods_name)) {
            title.setText("单套配置");
        }else {
            title.setText(goods_name);
        }



        initView();

        broadcastReceiver = BroadCastReceiverUtil.registerBroadcastReceiver(BashRoomListActivity.this, new String[]{ Constants.UPDATE_PRICE}, this);
    }

    private void initView() {
    /*    myScroll = (PullToRefreshScrollView) findViewById(R.id.myScroll);
        myScroll.setPullToRefreshOverScrollEnabled(false);*/
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        tv_right = (TextView) findViewById(R.id.tv_right);
        tv_right.setVisibility(View.VISIBLE);
        tv_right.setText("下一步");
        tv_right.setTextColor(0xff008c99);
        tv_right.setOnClickListener(this);
        my_recycler = (ListView) findViewById(R.id.my_recycler);
        if (null != getIntent()){
            packageId = getIntent().getStringExtra("packageId");
            money = getIntent().getStringExtra("money");
            skuId = getIntent().getStringExtra("skuId");
            type = getIntent().getStringExtra("type");
            shoppingMolder = (EntiretyShoppingMolder) getIntent().getSerializableExtra("molder");
            if(shoppingMolder==null){
                System.out.println("nulllllll");
            }else{
                System.out.println("fffflllllll");
            }
        }

        if (!TextUtils.isEmpty(packageId)){
            getBathSkuList(packageId);
        }

  /*      myScroll.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {


            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                myScroll.onRefreshComplete();
                if (!TextUtils.isEmpty(packageId)){
                    getBathSkuList(packageId);
                }

            }
        });*/
//        scrollView = myScroll.getRefreshableView();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.tv_right://下一步点击跳转
                if (MyUtils.isFastClick()) {

                            if ("C".equals(getIntent().getStringExtra("source"))) {
                                int goods = 0;
                                if (0 != bathRoomList.size()) {
                                    for (int i = 0; i < bathRoomList.size(); i++) {
                                        if (0 != bathRoomList.get(i).getChooseNum()) {
                                            goods = goods + 1;
                                        }
                                    }
                                    if (goods > 1) {
                                        MyToast("只能买一项!");
                                    } else if (goods == 0) {
                                        MyToast("请至少购买一项!");
                                    } else if (goods == 1) {
                                        int pos = 0;
                                        for (int i = 0; i < bathRoomList.size(); i++) {
                                            if (0 != bathRoomList.get(i).getChooseNum()) {
                                                pos = i;
                                            }
                                        }
                                        Intent intent = new Intent(BashRoomListActivity.this, AddCart2Activity.class);
                                        intent.putExtra("money", (chooseNum * Double.parseDouble(money)) + "");
                                        intent.putExtra("packageId", packageId);
                                        intent.putExtra("data", (Serializable) bathRoomList);
                                        intent.putExtra("skuId", bathRoomList.get(pos).getSku_id());
                                        intent.putExtra("nums", bathRoomList.get(pos).getChooseNum());
                                        intent.putExtra("molder", shoppingMolder);
                                        intent.putExtra("type", "0");
                                        intent.putExtra("price", bathRoomList.get(pos).getPrice());
                                        startActivity(intent);
                                        finish();

                                    }
                                }
                            }else if ("A".equals(getIntent().getStringExtra("source"))) {
                                if (0 != bathRoomList2.size()){
                                    bathRoomList2.clear();
                                }

                                if (0 != bathRoomList.size()) {
                                    for (int i = 0; i < bathRoomList.size(); i++) {
                                        if (0 != bathRoomList.get(i).getChooseNum()) {
                                            bathRoomList2.add(bathRoomList.get(i));
                                        }
                                    }
                                }
                                if (0 != bathRoomList2.size()) {

                                    int chooseNum = 0;
                                    for (int i = 0; i < bathRoomList2.size(); i++) {
                                        chooseNum += bathRoomList2.get(i).getChooseNum();
                                    }
                                Intent intent = new Intent(BashRoomListActivity.this, AddCart3Activity.class);
                                intent.putExtra("money", (chooseNum * Double.parseDouble(money)) + "");
                                intent.putExtra("packageId", packageId);
                                intent.putExtra("data", (Serializable) bathRoomList2);
                                intent.putExtra("skuId", skuId);
                                intent.putExtra("molder", shoppingMolder);
                                intent.putExtra("type", "0");
                                startActivity(intent);
                                finish();
                            }
                        }



//                    if (bathRoomList2.size()==1) {
//
//                        int chooseNum = 0;
//                        for (int i = 0; i < bathRoomList2.size(); i++) {
//                            chooseNum += bathRoomList2.get(i).getChooseNum();
//                        }
//
//                    }else if(bathRoomList2.size()==0){
//                        MyToast("请至少购买一项!");
//                    }else{
//                        MyToast("只能买一项!");
//                    }
                }
                break;

        }
    }


    //获得浴室sku列表 PACKAGE_SKU_LIST
    private void getBathSkuList(String packageId){
        Map<String,Object> params = new HashMap<>();
        params.put("packageId",packageId);
        params.put("token", MyApplication.getInstance().getUserBean().getToken());
        Set<String> set = params.keySet();
        for (String s : set) {
            Log.e("浴室列表的参数", s+" : "+params.get(s));
        }
        showDialog();
        XUtil.Post(Url.PACKAGE_SKU_LIST,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("result"))){
                        Gson gson = new Gson();
                        BathRoomSkuBean roomSkuBean = gson.fromJson(result,BathRoomSkuBean.class);

                        if (0 != bathRoomList.size()){
                            bathRoomList.clear();
                        }
                        if (null != roomSkuBean){
                            bathRoomList.addAll(roomSkuBean.getInfo());
                            mAdapter = new BashRoomAdapter(BashRoomListActivity.this, bathRoomList, my_recycler,money);
                            my_recycler.setAdapter(mAdapter);
                            mAdapter.notifyDataSetChanged();
                        }
                    }else if ("-1".equals(jsonObject.optString("result"))){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        MyToast(jsonObject.optString("info"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    //设置数据
    /**
     * can_buy == 1
       现价 = 前面的值+add_price
       原价 = price+add_price

       can_buy == 0
       现价 = oprice
       原价 = oprice
     */
   /* private void setBathRoomListAdatper(){
//        my_recycler.setLayoutManager(new LinearLayoutManager(BashRoomListActivity.this,LinearLayoutManager.VERTICAL,false));
        mBathRommAdapter = new BaseRVAdapter(BashRoomListActivity.this,bathRoomList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_bathroom_list;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                ImageView iv_img =  holder.getImageView(R.id.iv_img);//商品图片
                TextView tv_name = holder.getTextView(R.id.tv_name);//商品名字
                TextView tv_type = holder.getTextView(R.id.tv_type);//商品类型 如：整体浴室
                TextView tv_store = holder.getTextView(R.id.tv_store);//库存
                TextView tv_des = holder.getTextView(R.id.tv_des);//商品介绍
                LinearLayout ll_item = holder.getView(R.id.ll_item);//整个布局文件
                ImageView reduce = holder.getImageView(R.id.reduce);//减
                ImageView ll_add = holder.getImageView(R.id.ll_add);//加
                TextView now_price = holder.getTextView(R.id.now_price);//现价
                TextView original_price = holder.getTextView(R.id.original_price);//原价


                if ("1".equals(bathRoomList.get(position).getCan_buy())){
                    now_price.setText("¥" + (Double.parseDouble(money) + Double.parseDouble(bathRoomList.get(position).getAdd_price())));
                    original_price.setText("原价¥" + (Double.parseDouble(bathRoomList.get(position).getPrice())
                            + Double.parseDouble(bathRoomList.get(position).getAdd_price())));
                }else {//0
                    now_price.setText("¥" + bathRoomList.get(position).getOprice());
                    original_price.setText("原价¥" + bathRoomList.get(position).getOprice());
                }

                original_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                final TextView shopping_number = holder.getTextView(R.id.shopping_number);//购物车个数
                shopping_number.setText("" + 0);
                tv_des.setText(bathRoomList.get(position).getSku_info());

                Glide.with(BashRoomListActivity.this).load(bathRoomList.get(position).getImg()).error(R.mipmap.img_chanpinfenlei1).crossFade().into(iv_img);
                tv_name.setText(bathRoomList.get(position).getName());
                tv_type.setText(bathRoomList.get(position).getLabel());
                tv_store.setText("库存：" + bathRoomList.get(position).getStore());
                chooseNum = 0;
                deleteNum = 0;
                ll_add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {//加
                        chooseNum = Integer.parseInt(shopping_number.getText().toString());
                        if (chooseNum < Integer.parseInt(bathRoomList.get(position).getStore())){
                            chooseNum++;
                            shopping_number.setText("" + chooseNum);
                            bathRoomList.get(position).setChooseNum(chooseNum);

                            mBathRommAdapter = new BaseRVAdapter(this,my_recycler);
                        *//*    Intent intent = new Intent();
                            intent.putExtra("position",position);
                            intent.putExtra("bean", bathRoomList.get(position));
                            intent.setAction(Constants.UPDATE_PRICE_ADD);
                            BroadCastReceiverUtil.sendBroadcastByIntent(BashRoomListActivity.this, intent);
*//*
                        }else {
                            MyToast("不能再加了");
                        }
                    }
                });

                reduce.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {//减
                        deleteNum = Integer.parseInt(shopping_number.getText().toString());
                        if (deleteNum > 0){
                            deleteNum--;
                            shopping_number.setText("" + deleteNum);
                            bathRoomList.get(position).setChooseNum(deleteNum);

                          *//*  Intent intent = new Intent();
                            intent.putExtra("position",position);
                            intent.putExtra("bean", bathRoomList.get(position));
                            intent.setAction(Constants.UPDATE_PRICE_DEL);
                            BroadCastReceiverUtil.sendBroadcastByIntent(BashRoomListActivity.this, intent);*//*
                        }
                        else{
                            MyToast("不能再减了");
                        }
                    }
                });

                shopping_number.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        AlertDialog.Builder builder = new AlertDialog.Builder(BashRoomListActivity.this);
                        View view1 = View
                                .inflate(BashRoomListActivity.this, R.layout.dialog_edit_num, null);
                        builder.setView(view1);
                        builder.setCancelable(true);
                        TextView quxiao1= (TextView) view1
                                .findViewById(R.id.quxiao1);//取消
                        TextView queding1= (TextView) view1
                                .findViewById(R.id.queding1);//确定
                      final  EditText et_shopping_number=(EditText)view1.findViewById(R.id.shopping_number);
                        et_shopping_number.setText(shopping_number.getText().toString());

                       final AlertDialog dialog = builder.create();

                        queding1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                String lastnum = et_shopping_number.getText().toString();
                                if (!TextUtils.isEmpty(lastnum)) {
                                    int putNum = Integer.parseInt(lastnum);
                                    int store = Integer.parseInt(bathRoomList.get(position).getStore());
                                    if (putNum > store) {
                                        Toast.makeText(BashRoomListActivity.this, "已超过库存", Toast.LENGTH_SHORT).show();

                                        shopping_number.setText("" + store);
                                        dialog.dismiss();
                                    }else if(putNum==0||"".equals(shopping_number.getText().toString())){
                                        shopping_number.setText("0");
                                        bathRoomList.get(position).setChooseNum(0);
                                        dialog.dismiss();
                                    }
                                    else{

                                        if (lastnum.length() >= 2 && lastnum.startsWith("0")) {
                                            String resultnum = lastnum.replaceFirst("0", "");
                                            shopping_number.setText("" + resultnum);

                                        } else {
                                            shopping_number.setText("" + lastnum);
                                        }
                                        bathRoomList.get(position).setChooseNum(Integer.parseInt(shopping_number.getText().toString()));
                                        dialog.dismiss();
                                    }



                                } else {
                                    shopping_number.setText("0" );
                                }
                            }
                        });


                        quxiao1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });



                        dialog.show();
                    }
                });

            }

        };

        my_recycler.setAdapter(mBathRommAdapter);
        mBathRommAdapter.notifyDataSetChanged();
    }*/

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BroadCastReceiverUtil.unRegisterBroadcastReceiver(BashRoomListActivity.this, broadcastReceiver);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Message msg = new Message();
        if (intent.getAction().equals(Constants.UPDATE_PRICE)) {
//            if (MyUtils.isFastClick()) {
            BathRoomSkuBean.InfoEntity bean = (BathRoomSkuBean.InfoEntity) intent.getSerializableExtra("bean");
            msg.what = 100;
            msg.obj = bean;
            msg.arg1 = intent.getIntExtra("position", 0);
            mHandler.sendMessage(msg);
//            }
        }
    }

    private final MyHandler mHandler = new MyHandler(BashRoomListActivity.this);

    private class MyHandler extends Handler {
        //对Activity的弱引用
        private final WeakReference<BashRoomListActivity> mActivity;

        public MyHandler(BashRoomListActivity activity) {
            mActivity = new WeakReference<BashRoomListActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            BashRoomListActivity bashActivity = mActivity.get();
            if (bashActivity == null) {
                super.handleMessage(msg);
                return;
            }
            switch (msg.what) {
                case 100:
                    bashActivity.mAdapter.notifyDataSetChanged();
            }
        }
    }
    }
